package com.eschool.beans;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpServletRequest;

import com.eschool.model.ForumPost;
import com.eschool.model.User;
import com.eschool.service.CustomerService;
import com.eschool.service.impl.CustomerServiceImpl;
import com.eschool.util.UserUtil;

@ManagedBean(name = "viewPostBean")
@ViewScoped
public class ViewPostBean {

	private ForumPost parentPost;
	private List<ForumPost> childPosts;
	private int parentId;
	private CustomerService service = new CustomerServiceImpl();
	private String reply;
	private User currentUser;

	public ViewPostBean() {
		HttpServletRequest request = UserUtil.getRequest();
		parentId = Integer.parseInt(request.getParameter("id"));
		parentPost = service.getParentPost(parentId);
		childPosts = service.getAllChildPosts(parentId);
		currentUser = UserUtil.currentUser();

	}

	public ForumPost getParentPost() {
		return parentPost;
	}

	public void setParentPost(ForumPost parentPost) {
		this.parentPost = parentPost;
	}

	public List<ForumPost> getChildPosts() {
		return childPosts;
	}

	public void setChildPosts(List<ForumPost> childPosts) {
		this.childPosts = childPosts;
	}

	public String getReply() {
		return reply;
	}

	public void setReply(String reply) {
		this.reply = reply;
	}
	
	public void savePost(ActionEvent actionEvent) {
		ForumPost tempPost = new ForumPost();
		tempPost.setParentPost(parentPost);
		tempPost.setMessage(reply);
		tempPost.setPostTime(new Timestamp(new Date().getTime()));
		tempPost.setUser(currentUser);
		
		service.addForumPost(tempPost);
		childPosts = service.getAllChildPosts(parentId);
		setReply("");
		
		String message = "Reply Successfully Posted";
		FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Info message", message));
	}

}
